<template>
  <div id="map" class="map">
    <TyphoonInfo
      ref="typhoonInfo"
      :closeInfo="this.closeInfo"
      :typhoonData="typhoonData"
    />
  </div>
</template>

<script>
import "ol/ol.css";
import Map from "ol/Map";
import View from "ol/View";
import OSM from "ol/source/OSM";
import TileLayer from "ol/layer/Tile";
import { Vector as VectorLayer } from "ol/layer";
import { Vector as VectorSource } from "ol/source";
import Feature from "ol/Feature";
import { Point, LineString } from "ol/geom";
import { fromLonLat } from "ol/proj";
import { Fill, Circle, Style, Stroke } from "ol/style";
import XYZ from "ol/source/XYZ";
import { defaults as defaultControls } from "ol/control";
import { getDataCenterPoint, asnpoint, asnConnect } from "@/api/map";
import { resPdata1, resPdata2, resPdata3, resPdata4 } from "../json/mapJson";

import TyphoonInfo from "./typhoonInfo.vue";
import Overlay from "ol/Overlay";
export default {
  name: "HelloWorld",
  components: {
    TyphoonInfo,
  },
  data() {
    return {
      map: null,
      resPdata: [],
      lineData: [],
      linePointData: [],
      typhoonData: {},
      tfInfoOverlay: null,
      lastZoomPoint: null,
    };
  },

  mounted() {
    console.log("pppppppppppppp");
    this.initMap();
    this.getMap();
    this.addOverlay();
  },
  methods: {
    // 关闭窗口显示
    closeInfo: function () {
      this.tfInfoOverlay.setPosition(undefined);
    },

    // 添加弹框
    addOverlay: function () {
      var popup = new Overlay({
        element: this.$refs.typhoonInfo.$el,
        autoPan: true,
      });
      popup.setPosition(undefined);
      this.tfInfoOverlay = popup;
      this.map.addOverlay(popup);
    },
    // 初始化地图
    initMap() {
      this.map = new Map({
        layers: [
          new TileLayer({
            // 创建一个使用Open Street Map地图源的瓦片图层
            source: new XYZ({
              url: "https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}",
            }),
          }),
        ],
        target: "map",
        view: new View({
          zoom: 3, // 缩放
          // projection: 'EPSG:4326', // 坐标系
          center: [100.990969, 36.635013], // 地图中心点
          // center: [0,0]
        }),
        //加载控件到地图容器中
        controls: defaultControls({
          zoom: false,
          rotate: false,
          attribution: false,
        }),
      });
    },

    // 获取后台数据
    getMap() {
      // 获取点位数据
      asnpoint().then((res) => {
        if (res.code === 200) {
          asnConnect().then((res1) => {
            this.lineData = res1.data;
            this.drawTyphoonPath();
            this.drawLine();
            this.designClickOnMap();
          });
          // this.resPdata = res.data
          this.resPdata = res.data; //测试数据

          // console.log('this.resPdata', this.resPdata);
        }
      });
    },

    // 显示线
    drawLine() {
      let data = this.lineData;
      let len = data.length;
      let layer = new VectorLayer();
      let source = new VectorSource();

      // 创建线样式
      let redDashedLineStyle = new Style({
        stroke: new Stroke({
          color: "#286be9", // 线条颜色设置为红色
          width: 1, // 线条宽度
          // lineDash: [2, 3], // 虚线的模式，这里设置为10像素的实线和10像素的空白交替出现
        }),
      });
      // 创建绿色点样式
      let greenPointStyle = new Style({
        image: new Circle({
          radius: 2, // 点的大小
          fill: new Fill({
            color: "#7998bb", 
          }),
        }),
      });
      // 遍历lineData数组
      for (let i = 0; i < len; i++) {
        let currentData = data[i];
        let startPos = [currentData.srcLongitude, currentData.srcLatitude];
        let endPos = [currentData.dscLongitude, currentData.dscLatitude];

        // 创建线Feature
        let feature = new Feature({
          geometry: new LineString([fromLonLat(startPos), fromLonLat(endPos)]),
        });
        feature.setStyle(redDashedLineStyle); // 应用样式到Feature

        // 创建起点和终点的点Feature
        let startFeature = new Feature({
          geometry: new Point(fromLonLat(startPos)),
        });
        let endFeature = new Feature({
          geometry: new Point(fromLonLat(endPos)),
        });
        startFeature.setStyle(greenPointStyle);
        endFeature.setStyle(greenPointStyle); // 应用绿色点样式到终点Feature

        // 将Feature添加到VectorSource中
        source.addFeature(feature);
        source.addFeature(startFeature);
        source.addFeature(endFeature);
      }

      layer.setSource(source);
      this.map.addLayer(layer);
    },
    // 显示点
    drawTyphoonPath() {
      // let data = this.resPdata.filter(obj =>{ obj != null && obj.longitude && obj.latitude && obj.longitude > 0 && obj.latitude > 0 })
      // console.log(data)
      let data = [];
      for (var i = 0; i < this.resPdata.length; i++) {
        // console.log(this.resPdata[i])
        if (
          this.resPdata[i] &&
          this.resPdata[i].longitude &&
          this.resPdata[i].latitude &&
          this.resPdata[i].longitude > 0 &&
          this.resPdata[i].latitude > 0
        ) {
          data.push(this.resPdata[i]);
        }
      }

      let points = data;
      let features = [];
      let positions = [];
      for (let i = 0; i < data.length; i++) {
        let position = [points[i].longitude, points[i].latitude];
        var po = fromLonLat(position);
        // console.log(po)
        let featurePoint = new Feature({
          geometry: new Point(fromLonLat(position)),
        });

        featurePoint.setStyle(
          new Style({
            image: new Circle({
              fill: new Fill({
                color: "#00B0FF",
              }),
              radius: 6,
            }),
          })
        );

        // console.log('@@points', points[i]);
        console.log(`output->points[i]`, points[i]);
        featurePoint.set("pointData", points[i]);
        features.push(featurePoint);
      }
      // 矢量图层
      let layer = new VectorLayer();
      // 矢量数据源
      let source = new VectorSource();
      source.addFeatures(features);
      layer.setSource(source);
      this.map.addLayer(layer);
    },
   
    
    // 设置overlay position
    setOverlayPosition: function (position) {
      console.log(`output->position`, position);
      let transferPosition = fromLonLat(position);
      this.tfInfoOverlay.setPosition(transferPosition);
    },

    // 注册一个click事件
    designClickOnMap: function () {
      let _this = this;
      this.map.on("pointermove", function (ev) {
        console.log(`output->ev`, ev);
        let pixel = ev.pixel;
        let width = pixel[0] / _this.$store.state.switch.scaleS;
        let height = pixel[1] / _this.$store.state.switch.scaleS;
        let pix = [width, height];
        // console.log(pix)
        let feature = _this.map.forEachFeatureAtPixel(pix, function (feature) {
          return feature;
        });
        if (feature && feature.get("pointData")) {
          console.log(`output->`, feature);
          _this.map.getTargetElement().style.cursor = "pointer";
          feature.getStyle().getImage().setRadius(8);
          feature.changed();
          let point = feature.get("pointData");
          let position = [point.longitude, point.latitude];

          _this.lastZoomPoint = feature;
          console.log(point);
          _this.setOverlayPosition(position);
          _this.typhoonData = point;
          console.log(`output->this.typhoonData`, _this.typhoonData);
          // _this.$store.state.switch.showDetail = true;
          // console.log(`output->`, feature.values_.pointData)
        } else {
          _this.closeInfo();
          _this.clearPointZoomStyle();
          _this.map.getTargetElement().style.cursor = "";
          // console.log("no feature");
          _this.$store.state.switch.showDetail = false;
          _this.$store.state.switch.showDetailTwo = false;
        }
      });
    },
    // clearPoint Zoom Style
    clearPointZoomStyle: function () {
      let _this = this;
      if (_this.lastZoomPoint != null) {
        console.log(`output->`, name);
        _this.lastZoomPoint.getStyle().getImage().setRadius(6);
        _this.lastZoomPoint.changed();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.map {
  width: 100%;
  height: 100%;
}

</style>
